//
//  CORechargePresentController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/14.
//

import UIKit

class CORechargePresentController: SFPresentBottomViewController,SFPresentBottomViewControllerProtocol{
    
    var controllerHeight: CGFloat  = PTW(450) + KSafeBottomMargin
    var wallets = [COBalanceModel]() // 内购列表
    
    lazy var containerView: UIView = {
        let top = UIView()
        top.backgroundColor =  UIColor.colorWithHex("#D2D3D5")
        return top
    }()
    
    // 金币图片
    lazy var coinsImg:UIImageView = {
        let coin = UIImageView()
        coin.image = KImaged("coco_mine_star")
        return coin
    }()
    
    // 金币数
    lazy var coinsLbl:UILabel = {
        let coin = UILabel()
        coin.textColor = UIColor.colorWithHex("#8835FF")
        coin.font = UIFont.pingfangFont(ofSize:PTW(18), weight: .medium)
        let model = COUserInfoManager.shared.curUser
        coin.text = "\(model?.userResponse.balance ?? 0)"
        return coin
    }()

    lazy var baseTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = .clear
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 11.0, *) {
            if #available(iOS 13.0, *) {
                tableView.automaticallyAdjustsScrollIndicatorInsets = false
            }else{
                tableView.contentInsetAdjustmentBehavior = .never
            }
        }else {
            automaticallyAdjustsScrollViewInsets = false
        }
        return tableView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(containerView)
        containerView.addSubview(coinsLbl)
        containerView.addSubview(coinsImg)
        containerView.addSubview(baseTableView)
        containerView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(controllerHeight)
        }
        coinsLbl.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-PTW(15))
            make.top.equalToSuperview().offset(PTW(15))
            make.height.equalTo(PTW(21))
        }
        coinsImg.snp.makeConstraints { make in
            make.size.equalTo(PTW(25))
            make.trailing.equalTo(coinsLbl.snp.leading).offset(-PTW(5))
            make.centerY.equalTo(coinsLbl)
        }
        baseTableView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.top.equalTo(coinsImg.snp.bottom).offset(PTW(15))
        }
        loadWalletData()
    }
    
    func loadWalletData(){
        var params = [String:Any]()
        params["platform"]  = 2
        params["uuid"] = HDeviceIdentifier.deviceIdentifier()
        UIToolHelper.showHUD()
        COHttpManager.request(target: COBaseApi.priceList(param: params), modelType: COBalancePriceModel.self) {[weak self] code, object, success in
            UIToolHelper.hideHUD()
            self?.wallets.removeAll()
            self?.wallets = object?.prices ?? [COBalanceModel]()
            self?.baseTableView.reloadData()
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
            UIToolHelper.makeToast("Network error,plesase try again later!")
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.containerView.clipsCorners(corners: [.topLeft,.topRight], radius:PTW(20))
    }

    func dissMiss() {
        self.presentingViewController?.dismiss(animated: true, completion: nil)
    }
}

extension CORechargePresentController:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.wallets.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = COBalanceViewCell().cellWithTableView(tableView)
        cell.selectionStyle = .none
        if self.wallets.count > 0{
            cell.model = self.wallets[indexPath.row]
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = wallets[indexPath.row]
        guard model.productId != nil else {
            return
        }
        UIToolHelper.showHUD()
        AppPurchaseManager.pay(purchaseProductId: model.productId!) { result in
            UIToolHelper.hideHUD()
            if (result == true){
                UIToolHelper.makeToast("Successful!")
                AppPurchaseManager.updateBalance()
                COKVATrackerEvent.shared().clickBuyCoinsEvent(String(format: "%.2f", model.price))
            }else{
                UIToolHelper.makeToast("Fail,please try again later!")
            }
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.dissMiss()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return PTW(94)
    }
}
